package org.amphiprion.montrictracv4.fragment;

import java.util.ArrayList;
import java.util.List;

import org.amphiprion.montrictracv4.App;
import org.amphiprion.montrictracv4.ApplicationConstants.DATA_TYPE;
import org.amphiprion.montrictracv4.MainActivity;
import org.amphiprion.montrictracv4.R;
import org.amphiprion.montrictracv4.db.dao.SearchDao;
import org.amphiprion.montrictracv4.db.dao.UserCaracDao;
import org.amphiprion.montrictracv4.db.dao.UserInfoDao;
import org.amphiprion.montrictracv4.db.dao.UserMecanismDao;
import org.amphiprion.montrictracv4.db.model.Search;
import org.amphiprion.montrictracv4.db.model.UserGameData;
import org.amphiprion.montrictracv4.db.model.UserSearchData;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;

public class SearchEditFragment extends SherlockFragment implements TricTracFragment, View.OnClickListener {
	private View fragment;
	private LayoutInflater mInflater;

	private EditText txtName;
	private EditText txtAge;
	private EditText txtMinPlayer;
	private EditText txtMaxPlayer;
	private CheckBox cbExact;
	private EditText txtMinDuration;
	private EditText txtMaxDuration;

	private CheckBox chkInclideNoInfo;
	private LinearLayout llUserInfos;
	private CheckBox chkInclideNoCarac;
	private LinearLayout llUserCaracs;
	private CheckBox chkInclideNoMecanism;
	private LinearLayout llUserMecanisms;

	private List<UserSearchData> userInfos = new ArrayList<UserSearchData>();
	private List<UserSearchData> userCaracs = new ArrayList<UserSearchData>();
	private List<UserSearchData> userMecanisms = new ArrayList<UserSearchData>();

	private Search newSearch;

	private void initLayout() {
		llUserInfos = (LinearLayout) fragment.findViewById(R.id.llUserInfos);
		llUserCaracs = (LinearLayout) fragment.findViewById(R.id.llUserCaracs);
		llUserMecanisms = (LinearLayout) fragment.findViewById(R.id.llUserMecanisms);

		txtName = (EditText) fragment.findViewById(R.id.txtSearchName);
		txtAge = (EditText) fragment.findViewById(R.id.txtSearchAge);
		txtMinPlayer = (EditText) fragment.findViewById(R.id.txtSearchMinPlayer);
		txtMaxPlayer = (EditText) fragment.findViewById(R.id.txtSearchMaxPlayer);
		cbExact = (CheckBox) fragment.findViewById(R.id.chkSearchExact);
		txtMinDuration = (EditText) fragment.findViewById(R.id.txtSearchMinDuration);
		txtMaxDuration = (EditText) fragment.findViewById(R.id.txtSearchMaxDuration);

		chkInclideNoInfo = (CheckBox) fragment.findViewById(R.id.chkIncludeNoInfo);
		chkInclideNoCarac = (CheckBox) fragment.findViewById(R.id.chkIncludeNoCarac);
		chkInclideNoMecanism = (CheckBox) fragment.findViewById(R.id.chkIncludeNoMecanism);

		Button btCancel = (Button) fragment.findViewById(R.id.btCancel);
		btCancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				((InputMethodManager) getSherlockActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(txtName.getWindowToken(), 0);
				MainActivity.sThis.showSearchList();
			}
		});

		Button btSave = (Button) fragment.findViewById(R.id.btSave);
		btSave.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				((InputMethodManager) getSherlockActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(txtName.getWindowToken(), 0);
				save();
			}
		});

		ImageView btAddUserInfo = (ImageView) this.fragment.findViewById(R.id.btAddSearchInfo);
		btAddUserInfo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				addUserSearchInfo();
			}
		});

		ImageView btAddUserCarac = (ImageView) this.fragment.findViewById(R.id.btAddSearchCarac);
		btAddUserCarac.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				addUserSearchCarac();
			}
		});

		ImageView btAddUserMecanism = (ImageView) this.fragment.findViewById(R.id.btAddSearchMecanism);
		btAddUserMecanism.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				addUserSearchMecanism();
			}
		});

		if (App.currentSearch != null) {
			newSearch = App.currentSearch;
			initFragmentContent();
		} else {
			newSearch = new Search();
		}

	}

	private void addUserSearchInfo() {
		// select the user data
		final List<UserGameData> collections = UserInfoDao.getInstance(getSherlockActivity()).getAll(true);
		AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
		builder.setTitle(getResources().getString(R.string.info_comunity));
		builder.setAdapter(new ArrayAdapter<UserGameData>(getSherlockActivity(), android.R.layout.select_dialog_item, collections), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int item) {
				dialog.dismiss();
				UserGameData c = collections.get(item);
				if (c.typeForData == DATA_TYPE.FLOAT) {

					final UserSearchData usd = new UserSearchData(newSearch.getId(), c.dataId);
					usd.nameFromData = c.nameFromData;
					usd.typeForData = c.typeForData;

					userInfos.add(usd);
					final View v = mInflater.inflate(R.layout.user_search_data_row_float, null);
					((ImageView) v.findViewById(R.id.btDeleteUserSearchData)).setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v0) {
							llUserInfos.removeView(v);
							userInfos.remove(usd);
						}
					});

					llUserInfos.addView(v);
					usd._view = v;
					((TextView) v.findViewById(R.id.lblUserSearchData)).setText(usd.nameFromData);
				}
			}
		});
		AlertDialog alert = builder.create();
		alert.show();

	}

	private void addUserSearchCarac() {
		// select the user data
		final List<UserGameData> collections = UserCaracDao.getInstance(getSherlockActivity()).getAll(true);
		AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
		builder.setTitle(getResources().getString(R.string.carac_comunity));
		builder.setAdapter(new ArrayAdapter<UserGameData>(getSherlockActivity(), android.R.layout.select_dialog_item, collections), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int item) {
				dialog.dismiss();
				UserGameData c = collections.get(item);
				if (c.typeForData == DATA_TYPE.FLOAT) {

					final UserSearchData usd = new UserSearchData(newSearch.getId(), c.dataId);
					usd.nameFromData = c.nameFromData;
					usd.typeForData = c.typeForData;

					userCaracs.add(usd);
					final View v = mInflater.inflate(R.layout.user_search_data_row_float, null);
					((ImageView) v.findViewById(R.id.btDeleteUserSearchData)).setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v0) {
							llUserCaracs.removeView(v);
							userCaracs.remove(usd);
						}
					});

					llUserCaracs.addView(v);
					usd._view = v;
					((TextView) v.findViewById(R.id.lblUserSearchData)).setText(usd.nameFromData);
				}
			}
		});
		AlertDialog alert = builder.create();
		alert.show();

	}

	private void addUserSearchMecanism() {
		// select the user data
		final List<UserGameData> collections = UserMecanismDao.getInstance(getSherlockActivity()).getAll(true);
		AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
		builder.setTitle(getResources().getString(R.string.mecanism_comunity));
		builder.setAdapter(new ArrayAdapter<UserGameData>(getSherlockActivity(), android.R.layout.select_dialog_item, collections), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int item) {
				dialog.dismiss();
				UserGameData c = collections.get(item);
				if (c.typeForData == DATA_TYPE.FLOAT) {

					final UserSearchData usd = new UserSearchData(newSearch.getId(), c.dataId);
					usd.nameFromData = c.nameFromData;
					usd.typeForData = c.typeForData;

					userMecanisms.add(usd);
					final View v = mInflater.inflate(R.layout.user_search_data_row_float, null);
					((ImageView) v.findViewById(R.id.btDeleteUserSearchData)).setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v0) {
							llUserMecanisms.removeView(v);
							userMecanisms.remove(usd);
						}
					});

					llUserMecanisms.addView(v);
					usd._view = v;
					((TextView) v.findViewById(R.id.lblUserSearchData)).setText(usd.nameFromData);
				}
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private void initFragmentContent() {
		Search search = App.currentSearch;
		txtName.setText(search.name);
		convertToText(search.age, txtAge);
		convertToText(search.minPlayer, txtMinPlayer);
		convertToText(search.maxPlayer, txtMaxPlayer);
		cbExact.setChecked(search.exact);
		convertToText(search.minDuration, txtMinDuration);
		convertToText(search.maxDuration, txtMaxDuration);

		chkInclideNoInfo.setChecked(search.includeGameWithMissingInfo);
		chkInclideNoCarac.setChecked(search.includeGameWithMissingCarac);
		chkInclideNoMecanism.setChecked(search.includeGameWithMissingMecanism);
		// user infos
		llUserInfos.removeAllViews();
		for (final UserSearchData usd : search._userSearchInfos) {
			if (usd.typeForData == DATA_TYPE.FLOAT) {
				userInfos.add(usd);
				final View v = mInflater.inflate(R.layout.user_search_data_row_float, null);
				llUserInfos.addView(v);
				usd._view = v;

				((TextView) v.findViewById(R.id.lblUserSearchData)).setText(usd.nameFromData);
				if (usd.min_value > 0) {
					((EditText) v.findViewById(R.id.txtUserSearchDataMin)).setText("" + usd.min_value);
				}
				if (usd.max_value > 0) {
					((EditText) v.findViewById(R.id.txtUserSearchDataMax)).setText("" + usd.max_value);
				}

				((ImageView) v.findViewById(R.id.btDeleteUserSearchData)).setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v0) {
						llUserInfos.removeView(v);
						userInfos.remove(usd);
					}
				});
			}
		}

		// user caracs
		llUserCaracs.removeAllViews();
		for (final UserSearchData usd : search._userSearchCaracs) {
			if (usd.typeForData == DATA_TYPE.FLOAT) {
				userCaracs.add(usd);
				final View v = mInflater.inflate(R.layout.user_search_data_row_float, null);
				llUserCaracs.addView(v);
				usd._view = v;

				((TextView) v.findViewById(R.id.lblUserSearchData)).setText(usd.nameFromData);
				if (usd.min_value > 0) {
					((EditText) v.findViewById(R.id.txtUserSearchDataMin)).setText("" + usd.min_value);
				}
				if (usd.max_value > 0) {
					((EditText) v.findViewById(R.id.txtUserSearchDataMax)).setText("" + usd.max_value);
				}
				((ImageView) v.findViewById(R.id.btDeleteUserSearchData)).setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v0) {
						llUserCaracs.removeView(v);
						userCaracs.remove(usd);
					}
				});

			}
		}

		// user mecanisms
		llUserMecanisms.removeAllViews();
		for (final UserSearchData usd : search._userSearchMecanisms) {
			if (usd.typeForData == DATA_TYPE.FLOAT) {
				userMecanisms.add(usd);
				final View v = mInflater.inflate(R.layout.user_search_data_row_float, null);
				llUserMecanisms.addView(v);
				usd._view = v;

				((TextView) v.findViewById(R.id.lblUserSearchData)).setText(usd.nameFromData);
				if (usd.min_value > 0) {
					((EditText) v.findViewById(R.id.txtUserSearchDataMin)).setText("" + usd.min_value);
				}
				if (usd.max_value > 0) {
					((EditText) v.findViewById(R.id.txtUserSearchDataMax)).setText("" + usd.max_value);
				}
				((ImageView) v.findViewById(R.id.btDeleteUserSearchData)).setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v0) {
						llUserMecanisms.removeView(v);
						userMecanisms.remove(usd);
					}
				});
			}
		}
	}

	private void convertToText(int value, EditText txt) {
		if (value > 0) {
			txt.setText("" + value);
		} else {
			txt.setText("");
		}
	}

	private void save() {
		Search search = App.currentSearch;
		if (search == null) {
			search = new Search();
		}
		search.name = txtName.getText().toString();
		search.age = convertToInt(txtAge, 0);
		search.minPlayer = convertToInt(txtMinPlayer, 0);
		search.maxPlayer = convertToInt(txtMaxPlayer, 0);
		search.exact = cbExact.isChecked();
		search.minDuration = convertToInt(txtMinDuration, 0);
		search.maxDuration = convertToInt(txtMaxDuration, 0);

		search.includeGameWithMissingInfo = chkInclideNoInfo.isChecked();
		search.includeGameWithMissingCarac = chkInclideNoCarac.isChecked();
		search.includeGameWithMissingMecanism = chkInclideNoMecanism.isChecked();
		// user infos:
		search._userSearchInfos.clear();
		for (UserSearchData usd : userInfos) {
			usd.searchId = search.getId();
			EditText txt = (EditText) usd._view.findViewById(R.id.txtUserSearchDataMin);
			usd.min_value = convertToInt(txt, 0);

			txt = (EditText) usd._view.findViewById(R.id.txtUserSearchDataMax);
			usd.max_value = convertToInt(txt, 0);

			if (usd.min_value != 0 || usd.max_value != 0) {
				search._userSearchInfos.add(usd);
			}
		}

		// user caracs
		search._userSearchCaracs.clear();
		for (UserSearchData usd : userCaracs) {
			usd.searchId = search.getId();
			EditText txt = (EditText) usd._view.findViewById(R.id.txtUserSearchDataMin);
			usd.min_value = convertToInt(txt, 0);

			txt = (EditText) usd._view.findViewById(R.id.txtUserSearchDataMax);
			usd.max_value = convertToInt(txt, 0);

			if (usd.min_value != 0 || usd.max_value != 0) {
				search._userSearchCaracs.add(usd);
			}
		}

		// user mecanism
		search._userSearchMecanisms.clear();
		for (UserSearchData usd : userMecanisms) {
			usd.searchId = search.getId();
			EditText txt = (EditText) usd._view.findViewById(R.id.txtUserSearchDataMin);
			usd.min_value = convertToInt(txt, 0);

			txt = (EditText) usd._view.findViewById(R.id.txtUserSearchDataMax);
			usd.max_value = convertToInt(txt, 0);

			if (usd.min_value != 0 || usd.max_value != 0) {
				search._userSearchMecanisms.add(usd);
			}
		}

		SearchDao.getInstance(getSherlockActivity()).persist(search);
		MainActivity.sThis.showSearchList();
	}

	private int convertToInt(EditText txt, int defaultValue) {
		try {
			return Integer.parseInt(txt.getText().toString());
		} catch (Throwable e) {
			return defaultValue;
		}
	}

	@Override
	public void onActivityCreated(Bundle paramBundle) {
		super.onActivityCreated(paramBundle);
		initLayout();
	}

	@Override
	public void onClick(View paramView) {
		// switch (paramView.getId()) {
		// case R.id.edit:
		// toggleEdit();
		// return;
		// }

	}

	@Override
	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
	}

	@Override
	public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
		super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);
		this.mInflater = paramLayoutInflater;
		this.fragment = this.mInflater.inflate(R.layout.fragment_search_edit, paramViewGroup, false);

		return this.fragment;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void menuOptionClicked(int id) {

	}

	@Override
	public void refresh() {

	}

}